import {Divider, Popconfirm, Input, DatePicker, Modal, Button, Upload, message} from 'antd'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import React, {useState, useEffect} from 'react'
import styles from "@/pages/Info/Edit/style.less";
import { UploadOutlined } from '@ant-design/icons';
import {connect} from 'umi'
import {protocolStatus, genderList} from "@/utils/constant";
import {saveProtocolInfo, updateProtocolPersonnelStatusFive} from '../../service'
import {getUploadUrl} from "@/utils/upload";
import moment from 'moment'

const {RangePicker} = DatePicker;

const TableForm = ({addUserList, protocolUserItems=[], saveFunction, hideOperate}) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [loading, setLoading] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [data, setData] = useState([]);
  const [visible, setVisible] = useState(false);
  const [protocolId, setProtocolId] = useState(null);
  const [fileName, setFileName] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [uploadFileUrl, setUploadFileUrl] = useState('');

  const props = {
    name: 'file',
    fileList,
    multiple: false,
    action: getUploadUrl(),
    accept: ".pdf",
    data: {name: '(线下签署)'+fileName, catlog: 'contract'},
    beforeUpload(file) {
      if (fileList.length>0){
        message.error('已超出上传文件数目限制！');
        return false;
      }
      setFileName(file.name)
    },
    onChange(info) {
      const {status} = info.file;
      setFileList(info.fileList.filter(file => !!file.status));
      if (status === 'done') {
        setUploadFileUrl(info.file.response);
        message.success(`${info.file.name} 文件上传成功`);
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileList;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileList([urls]);
    }
  };

  let columns = [
    {
      title: '工号',
      dataIndex: 'code',
      key: 'code',
      disabled: true
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      disabled: true
    },
    {
      title: '身份证号码',
      dataIndex: 'idcard',
      key: 'idcard',
      disabled: true
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      disabled: true,
      render: (text) => genderList.find(item => item.value===text)?.label
    },
    {
      title: '部门',
      dataIndex: 'unitname',
      key: 'unitname',
      disabled: true
    },
    {
      title: '岗位',
      dataIndex: 'jobname',
      key: 'jobname',
      disabled: true
    },
    {
      title: '培训学杂费',
      dataIndex: 'trainingSpending',
      key: 'trainingSpending',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input value={text==='-'?'':text} type='number' onChange={(e) => handleFieldChange(e, 'trainingSpending', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '往返交通住宿伙食费',
      dataIndex: 'trainingFoodSpending',
      key: 'trainingFoodSpending',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input value={text==='-'?'':text} type='number' onChange={(e) => handleFieldChange(e, 'trainingFoodSpending', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '培训费用合计',
      dataIndex: 'trainingTotal',
      key: 'trainingTotal',
      render: (text, record) => {
        return text
      },
    },
    {
      title: '服务期限起止日期',
      dataIndex: 'serviceTime ',
      key: 'serviceTime',
      render: (text, record) => {
        if (record.editable) {
          let data = [];
          if (record.serviceTime?.length===2)
            data = [moment(record.serviceTime[0]),moment(record.serviceTime[1])];
          return (
            <RangePicker value={data} className='widthStyle' onCalendarChange={value => handleFieldChange(value, 'serviceTime', record.key)} />
          )
        }
        return record.serviceTime?.length===2 && `${moment(record.serviceTime[0]).format('YYYY-MM-DD')} - ${moment(record.serviceTime[1]).format('YYYY-MM-DD')}`
      },
    },
    {
      title: '培训协议签订状态',
      dataIndex: 'status',
      key: 'status',
      disabled: true,
      hideInTable: !hideOperate,
      valueEnum: {
        0: { text: protocolStatus[0].label, status: 'Default'},
        1: { text: protocolStatus[1].label, status: 'Processing'},
        2: { text: protocolStatus[2].label, status: 'Success'},
        3: { text: protocolStatus[3].label, status: 'Warning'},
        4: { text: protocolStatus[4].label, status: 'Error'},
      },
    },
    {
      title: '操作',
      key: 'action',
      width: '150px',
      render: (text, record) => {
        if (hideOperate) {
          if (record.status===0||record.status===1){
            return <>
              <a onClick={(e) => sendSigned(record.id)}>发起协议签订</a>
              <Divider type="vertical"/>
              <a onClick={(e) => showUploadModal(record.id)}>线下签订</a>
            </>
          }
        }else {
          if (record.editable) {
            return (
              <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
            )
          }
          return (
            <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否确定删除？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record)}>
              <a>删除</a>
            </Popconfirm>
          </span>
          )
        }

      },
    },
  ];

  useEffect(()=>{
    setData(protocolUserItems.map((item, index) => ({key: 'had' + index, ...item})));
  },[protocolUserItems]);

  useEffect(() => {
    setLoading(true);
    if (addUserList.length > 0) {
      let newData = [...data];
      for (let i = 0; i < addUserList.length; i++) {
        let isContinue = false;
        for (let a = 0; a < data.length; a++) {
          if (data[a].oid === addUserList[i].oid)
            isContinue = true;
        }
        if (isContinue)
          continue;
        newData.push({
          id: null,
          key: addUserList[i].oid,
          code: addUserList[i].code,
          idcard: addUserList[i].idcard,
          gender: addUserList[i].gender,
          orgname: addUserList[i].orgname,
          unitname: addUserList[i].unitname,
          jobname: addUserList[i].jobname,
          oid: addUserList[i].oid,
          name: addUserList[i].name,
        });
      }
      saveFunction(newData);
    }
    setLoading(false);
  }, [addUserList]);

  const sendSigned = (id) => {
    saveProtocolInfo(id).then(res => {
      if (res.flag){
        message.success('发送协议签订成功');
      }else {
        message.error(res.error);
      }
    })
  };

  const handleCancel = () => {
    setVisible(false);
    setProtocolId(null);
  };

  const showUploadModal = (id) => {
    setVisible(true);
    setProtocolId(id);
  };

  const hadSigned = () => {
    updateProtocolPersonnelStatusFive({id: protocolId, contractOssUrl: uploadFileUrl}).then(res => {
      if (res.flag){
        message.success('设置线下签署成功！');
        let newData = [...data];
        newData.find(item => item.id===protocolId).status = 2;
        saveFunction(newData);-
          setVisible(false);
        setProtocolId(null);
      }else {
        message.error(res.error);
      }
    })
  };

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0]

  const toggleEditable = (e, key, type) => {
    e.preventDefault();
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      if (type === 'save'){
        saveFunction(newData)
      }else {
        setData(newData);
      }
    }
  };

  const remove = (e, record) => {
    setLoading(true);
    const newData = [...data];
    let datas = newData.filter(item => item.key !== record.key);
    saveFunction(datas);
    setLoading(false);
  };

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = (e && e.target) ? e.target.value : e;
      if (fieldName==='trainingSpending' || fieldName==='trainingFoodSpending'){
        let trainingSpending = target.trainingSpending ? parseFloat(target.trainingSpending) : 0;
        let trainingFoodSpending = target.trainingFoodSpending ? parseFloat(target.trainingFoodSpending) : 0;
        target.trainingTotal = (trainingSpending + trainingFoodSpending).toFixed(2);
      }else if (fieldName==='serviceTime' && (target[fieldName].findIndex(item => !item) !== -1)){
        target.serviceTime = [];
      }
      setData(newData)
    }
  }

  const updateRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    toggleEditable(e, rowKey, 'save');
  }

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data]; // 编辑前的原始数据
    let cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = {...cacheOriginData[key], editable: false};
          delete cacheOriginData[key];
          setCacheOriginData(cacheOriginData);
          return originItem
        }
      }
      return item
    });
    saveFunction(cacheData);
    setClickedCancel(false)
  };

  return (
    <>
      <ProTable
        toolBarRender={false}
        loading={loading}
        columns={columns}
        dataSource={data}
        search={false}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
      />

      <Modal title="上传线下签署附件" visible={visible} onOk={hadSigned} onCancel={handleCancel}>
        <Upload {...props}>
          <Button icon={<UploadOutlined />}>上传线下签署pdf附件</Button>
        </Upload>
      </Modal>

    </>
  )
}

export default connect(({  }) => ({

}))(TableForm)

